import yaml
import argparse

def sort_key(item):
    value = item[1]
    # Priority for books
    type_priority = 0 if value.get('type', '') == 'Book' else 1
    # Priority for Russian language sources
    language_priority = 0 if value.get('language', '').startswith('ru') else 1
    return (type_priority, language_priority, value.get('author', ''), value.get('date', ''), value.get('language', ''))

def sort_yaml(in_file, out_file):
    # Read YAML data from the input file
    with open(in_file, 'r', encoding='utf-8') as file:
        data = yaml.safe_load(file)

    # Sort the data
    sorted_data = dict(sorted(data.items(), key=sort_key))

    # Generate sorted YAML content
    sorted_yaml_content = yaml.dump(sorted_data, allow_unicode=True, sort_keys=False, default_flow_style=False)

    # Save the sorted YAML content to the output file
    with open(out_file, 'w', encoding='utf-8') as file:
        file.write(sorted_yaml_content)

if __name__ == "__main__":
    # Command line arguments setup
    parser = argparse.ArgumentParser(description='Sort YAML file according to ГОСТ Р 7.0.5–2008')
    parser.add_argument('inFile', type=str, help='Input YAML file')
    parser.add_argument('outFile', type=str, help='Output YAML file')

    args = parser.parse_args()

    # Sort the YAML file
    sort_yaml(args.inFile, args.outFile)
